"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 系统内部使用工具
Case Name   : 执行gs_postuninstall命令清理环境，不指定-l，且不在XML文件中配置gaussdbLogPath
Create At   : 2021/12/28
Owner       : @daiguatutu
Description :
    1.下载解压数据库安装包
    2.配置xml文件,不配置gaussdbLogPath
    3.创建好初始用户并修改文件属组
    4.在script目录下，执行gs_preinstall命令：
    ./gs_preinstall -U [自定义初始用户] -G [自定义初始用户组] -X [xml配置文件路径]
    --sep-env-file=[env文件路径]  --non-interactive  --skip-hostname-set
    5.执行postuninstall命令：
    ./gs_postuninstall -U [自定义初始用户]  -X [xml配置文件路径]
    --delete-user --delete-group
    6.清理环境：
    rm -rf [数据库相关目录]
Expect      :
    1.下载解压成功
    2.配置成功
    3.创建成功
    4.预安装成功
    5.执行成功,默认目录/var/log/gaussdb/用户名/om/无日志文件
    6.清理成功
History     :
    modified by @daiguatutu at 2023-5-22:添加hosts文件的备份和恢复，避免hosts文件被破坏
"""
import os
import re
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro

Primary_node = Node('PrimaryDbUser')
Constant = Constant()

wget_result = Primary_node.sh(f"wget {macro.FTP_PATH} -c -t2 -T30").result()


@unittest.skipIf(re.search(Constant.wget_connect_success_msg, wget_result)
                 is None, 'wget连接失败')
class Tools(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        primary_sh = CommonSH('PrimaryDbUser')
        if primary_sh.get_node_num() == 1:
            self.root_node = Node('PrimaryRoot')
            self.node = Node('PrimaryDbUser')
        else:
            self.root_node = Node('Standby2Root')
            self.node = Node('Standby2DbUser')
        self.common = Common()
        self.u_name = f'u_gs_install_{os.path.basename(__file__)[-7:-3]}'
        self.u_name = 'u_gs_postuninstall_0002'
        path = macro.DB_INSTANCE_PATH
        for i in range(len(path.split('/')) - 2):
            path = os.path.dirname(path)
        self.openGauss_path = os.path.join(path, 'dir_gs_postuninstall_0002')
        self.package_path = os.path.join(self.openGauss_path, 'pkg')
        self.conf_path = os.path.join(self.openGauss_path, 'config')
        self.data_path = os.path.join(self.openGauss_path, 'cluster')
        self.xml_path = os.path.join(self.conf_path, 'single.xml')
        self.env_path = os.path.join(self.conf_path, 'env')
        self.script_path = os.path.join(self.package_path, 'script')

        text = '-----备份/etc/hosts文件-----'
        self.log.info(text)
        self.host_file = os.path.join('/', 'etc', 'hosts')
        self.host_bk = os.path.join(path, 'hosts_install_bk')
        hosts_cmd = f"cp {self.host_file} {self.host_bk};"
        msg = self.common.get_sh_result(self.root_node, hosts_cmd)
        self.assertEqual('', msg, '执行失败:' + text)

    def test_standby(self):
        text = '-----step1:下载解压数据库安装包 expect:下载解压成功-----'
        self.log.info(text)
        self.common.check_load_msg(self.root_node, self.node,
                                   self.package_path, self.conf_path)

        test = '-----查看主机名-----'
        self.log.info(test)
        node_name = self.root_node.sh("uname -n").result()
        self.log.info(node_name)
        self.assertIsNotNone(node_name, '执行失败:' + text)

        test = '-----查询系统未使用端口-----'
        self.log.info(test)
        port = self.common.get_not_used_port(self.node)
        self.assertNotEqual(0, port, '执行失败:' + text)

        text = '-----step2:配置xml文件,不配置gaussdbLogPath expect:配置成功-----'
        self.log.info(text)
        gaussdb_app_path = os.path.join(self.data_path, 'app')
        tmpmppdb_path = os.path.join(self.data_path, 'tmp')
        gaussdb_tool_path = os.path.join(self.data_path, 'tool')
        data_node1 = os.path.join(self.data_path, 'dn1')
        self.common.scp_file(self.root_node, 'single.xml', self.conf_path)
        xml_cmd = f"sed -i 's#v_nodeNames#{node_name}#g' {self.xml_path};" \
            f"sed -i 's#v_gaussdbAppPath#{gaussdb_app_path}#g' " \
            f"{self.xml_path};" \
            f"sed -i '/gaussdbLogPath/d' {self.xml_path};" \
            f"sed -i 's#v_tmpMppdbPath#{tmpmppdb_path}#g' " \
            f"{self.xml_path};" \
            f"sed -i 's#v_gaussdbToolPath#{gaussdb_tool_path}#g' " \
            f"{self.xml_path};" \
            f"sed -i 's#v_corePath#{macro.DB_CORE_PATH}#g' {self.xml_path};" \
            f"sed -i 's#v_db_host#{self.node.db_host}#g' " \
            f"{self.xml_path};" \
            f"sed -i 's#v_dataPortBase#{port}#g' {self.xml_path};" \
            f"sed -i 's#v_dataNode1#{data_node1}#g' {self.xml_path};" \
            f"cat {self.xml_path}"
        self.log.info(xml_cmd)
        result = self.root_node.sh(xml_cmd).result()
        self.log.info(result)
        msg_list = [node_name, self.data_path, f"{port}", self.node.db_host]
        for content in msg_list:
            self.assertTrue(result.find(content) > -1, '执行失败:' + text)
        self.assertNotIn('gaussdbLogPath', result, '执行失败:' + text)

        text = '-----step3:创建初始用户并修改属组 expect:成功-----'
        self.log.info(text)
        self.common.create_user(self.root_node, self.u_name)
        file_own = f'chown -R {self.u_name}:{self.u_name} ' \
            f'{self.openGauss_path};'
        self.log.info(file_own)
        file_msg = self.root_node.sh(file_own).result()
        self.log.info(file_msg)
        self.assertEqual('', file_msg, '执行失败:' + test)

        text = '-----step4:在script目录下，执行gs_preinstall命令 expect:预安装成功-----'
        self.log.info(text)
        preinstall_cmd = f"cd {self.script_path};" \
            f"./gs_preinstall -U {self.u_name} -G {self.u_name} " \
            f"-X {self.xml_path} --sep-env-file={self.env_path} " \
            f"--non-interactive --skip-hostname-set"
        self.log.info(preinstall_cmd)
        msg = self.root_node.sh(preinstall_cmd).result()
        self.log.info(msg)
        self.assertIn(Constant.preinstall_success_msg, msg,
                      '执行失败:' + text)

        text = '-----step5:执行gs_postuninstall expect:成功,默认log目录下无日志文件-----'
        self.log.info(text)
        gaussdb_path = os.path.join('/', 'var', 'log', 'gaussdb')
        gaussdb_log = os.path.join(gaussdb_path, self.u_name, 'om')
        postuninstall_cmd = f'source {self.env_path};' \
            f'{self.script_path}/gs_postuninstall  -U {self.u_name}  ' \
            f'-X {self.xml_path} --delete-user --delete-group'
        postuninstall_msg = self.root_node.sh(
            postuninstall_cmd).result()
        self.log.info(postuninstall_msg)
        self.assertIn(Constant.postuninstall_success_msg,
                      postuninstall_msg, '执行失败:' + text)
        cmd = f'chown root:root {gaussdb_path};' \
            f'chmod 755 {gaussdb_path};' \
            f'cd {gaussdb_log};' \
            f'du -sh *'
        self.log.info(cmd)
        msg = self.root_node.sh(cmd).result()
        self.log.info(msg)
        self.assertEqual('0', msg.split()[0], '执行失败:' + text)
        self.assertEqual(2, len(msg.split()), '执行失败:' + text)

    def tearDown(self):
        self.log.info('-----step6:清理环境-----')
        text_1 = '-----恢复hosts文件 expect:成功-----'
        self.log.info(text_1)
        hosts_cmd = f'if [[ -e {self.host_file} && -e {self.host_bk} ]]; ' \
            f'then rm -rf {self.host_file}; ' \
            f'mv {self.host_bk} {self.host_file}; ' \
            f'else echo not exits; fi'
        hosts_msg = self.common.get_sh_result(self.root_node, hosts_cmd)

        text_2 = '-----删除用户下进程 expect:成功-----'
        self.log.info(text_2)
        kill_cmd = f"ps -u {self.u_name} | grep -v PID| " \
            f"awk \'{{{{print $1}}}}\' | xargs kill -9"
        self.common.get_sh_result(self.root_node, kill_cmd)

        text_3 = '-----删除用户 expect:成功-----'
        self.log.info(text_3)
        udel_cmd = f'userdel -r {self.u_name};userdel -r {self.u_name};'
        udel_msg = self.common.get_sh_result(self.root_node, udel_cmd)

        text_4 = '-----删除数据准备目录 expect:成功-----'
        self.log.info(text_4)
        del_cmd = f'rm -rf {self.openGauss_path}'
        self.common.get_sh_result(self.root_node, del_cmd)
        check_cmd = f'if [ -d {self.openGauss_path} ]; ' \
            f'then echo "exists"; else echo "not exists"; fi'
        del_msg = self.common.get_sh_result(self.root_node, check_cmd)

        self.assertEqual('', hosts_msg, '执行失败:' + text_1)
        self.assertIn('not exist', udel_msg, '执行失败:' + text_3)
        self.assertEqual('not exists', del_msg, '执行失败:' + text_4)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
